import Dialog from 'tdesign-miniprogram/dialog/index';
import Toast from 'tdesign-miniprogram/toast/index';
import { fetchCartGroupData } from '../../services/cart/cart';
import { getOutfitList, deleteOutfit, getOccasionList } from '../../services/outfit/outfit';
import clothesData from '../../data/clothesData';

// 模拟的静态搭配方案数据
const staticOutfitList = [
  // 搭配方案 1：春季日常休闲
  {
    id: 1,
    name: "春季日常休闲搭配",
    season: "春",
    occasionName: "日常",
    occasion: "日常",
    image: "/images/clothes/white-tshirt.jpg",
    clothesNames: "白色棉质T恤、深蓝色牛仔裤、牛仔外套",
    clothes: [
      { id: 1, name: "白色棉质T恤", type: "上衣", season: ["春", "夏", "秋"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "基础款白色T恤", size: "M", imageUrl: "/images/clothes/white-tshirt.jpg" },
      { id: 2, name: "深蓝色牛仔裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "修身款牛仔裤", size: "32", imageUrl: "/images/clothes/blue-jeans.png" },
      { id: 11, name: "牛仔外套", type: "外套", season: ["春", "秋"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "经典牛仔外套", size: "M", imageUrl: "/images/clothes/denim-jacket.jpg" }
    ]
  },
  // 搭配方案 2：冬季工作保暖
  {
    id: 2,
    name: "冬季工作保暖搭配",
    season: "冬",
    occasionName: "工作",
    occasion: "工作",
    image: "/images/clothes/wool-coat.jpg",
    clothesNames: "羊毛大衣、高领毛衣、西装裤",
    clothes: [
      { id: 6, name: "羊毛大衣", type: "外套", season: ["冬"], isDirty: false, isMoldy: false, isDamaged: true, cleaningStatus: "已清洗", maintenanceStatus: "待保养", description: "深灰色羊毛大衣", size: "L", imageUrl: "/images/clothes/wool-coat.jpg" },
      { id: 16, name: "高领毛衣", type: "上衣", season: ["秋", "冬"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "灰色高领毛衣", size: "M", imageUrl: "/images/clothes/turtleneck.jpg" },
      { id: 20, name: "西装裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "黑色西装裤", size: "32", imageUrl: "/images/clothes/suit-pants.jpg" }
    ]
  },
  // 搭配方案 3：夏季日常休闲
  {
    id: 3,
    name: "夏季日常休闲搭配",
    season: "夏",
    occasionName: "日常",
    occasion: "日常",
    image: "/images/clothes/white-tshirt.jpg",
    clothesNames: "白色棉质T恤、运动短裤",
    clothes: [
      { id: 1, name: "白色棉质T恤", type: "上衣", season: ["春", "夏", "秋"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "基础款白色T恤", size: "M", imageUrl: "/images/clothes/white-tshirt.jpg" },
      { id: 5, name: "运动短裤", type: "裤装", season: ["夏"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "速干面料运动短裤", size: "M", imageUrl: "/images/clothes/sports-shorts.jpg" }
    ]
  },
  // 搭配方案 4：秋季工作通勤
  {
    id: 4,
    name: "秋季工作通勤搭配",
    season: "秋",
    occasionName: "工作",
    occasion: "工作",
    image: "/images/clothes/blazer.jpg",
    clothesNames: "休闲西装、真丝衬衫、休闲裤",
    clothes: [
      { id: 8, name: "休闲西装", type: "外套", season: ["春", "秋"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "深蓝色休闲西装", size: "M", imageUrl: "/images/clothes/blazer.jpg" },
      { id: 10, name: "真丝衬衫", type: "上衣", season: ["春", "夏"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "米色真丝衬衫", size: "S", imageUrl: "/images/clothes/silk-blouse.jpg" },
      { id: 17, name: "休闲裤", type: "裤装", season: ["春", "秋"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "卡其色休闲裤", size: "32", imageUrl: "/images/clothes/chinos.jpg" }
    ]
  },
  // 搭配方案 5：春季运动休闲
  {
    id: 5,
    name: "春季运动休闲搭配",
    season: "春",
    occasionName: "运动",
    occasion: "运动",
    image: "/images/clothes/hoodie.jpg",
    clothesNames: "运动卫衣、运动裤",
    clothes: [
      { id: 9, name: "运动卫衣", type: "上衣", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "连帽卫衣", size: "L", imageUrl: "/images/clothes/hoodie.jpg" },
      { id: 13, name: "运动裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "黑色运动裤", size: "L", imageUrl: "/images/clothes/sweatpants.jpg" }
    ]
  },
  // 搭配方案 6：冬季正式场合
  {
    id: 6,
    name: "冬季正式场合搭配",
    season: "冬",
    occasionName: "正式",
    occasion: "正式",
    image: "/images/clothes/wool-coat.jpg",
    clothesNames: "羊毛大衣、真丝衬衫、西装裤",
    clothes: [
      { id: 6, name: "羊毛大衣", type: "外套", season: ["冬"], isDirty: false, isMoldy: false, isDamaged: true, cleaningStatus: "已清洗", maintenanceStatus: "待保养", description: "深灰色羊毛大衣", size: "L", imageUrl: "/images/clothes/wool-coat.jpg" },
      { id: 10, name: "真丝衬衫", type: "上衣", season: ["春", "夏"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "米色真丝衬衫", size: "S", imageUrl: "/images/clothes/silk-blouse.jpg" },
      { id: 20, name: "西装裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "黑色西装裤", size: "32", imageUrl: "/images/clothes/suit-pants.jpg" }
    ]
  },
  // 搭配方案 7：夏季日常裙装
  {
    id: 7,
    name: "夏季日常裙装搭配",
    season: "夏",
    occasionName: "日常",
    occasion: "日常",
    image: "/images/clothes/floral-dress.jpg",
    clothesNames: "连衣裙",
    clothes: [
      { id: 7, name: "连衣裙", type: "裙装", season: ["春", "夏"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "碎花连衣裙", size: "S", imageUrl: "/images/clothes/floral-dress.jpg" }
    ]
  },
  // 搭配方案 8：秋季休闲
  {
    id: 8,
    name: "秋季休闲搭配",
    season: "秋",
    occasionName: "休闲",
    occasion: "休闲",
    image: "/images/clothes/plaid-shirt.jpg",
    clothesNames: "格子衬衫、深蓝色牛仔裤",
    clothes: [
      { id: 4, name: "格子衬衫", type: "上衣", season: ["春", "秋"], isDirty: false, isMoldy: true, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "经典红黑格子衬衫", size: "S", imageUrl: "/images/clothes/plaid-shirt.jpg" },
      { id: 2, name: "深蓝色牛仔裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "修身款牛仔裤", size: "32", imageUrl: "/images/clothes/blue-jeans.png" }
    ]
  },
  // 搭配方案 9：春季工作
  {
    id: 9,
    name: "春季工作搭配",
    season: "春",
    occasionName: "工作",
    occasion: "工作",
    image: "/images/clothes/blazer.jpg",
    clothesNames: "休闲西装、白色棉质T恤、休闲裤",
    clothes: [
      { id: 8, name: "休闲西装", type: "外套", season: ["春", "秋"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "深蓝色休闲西装", size: "M", imageUrl: "/images/clothes/blazer.jpg" },
      { id: 1, name: "白色棉质T恤", type: "上衣", season: ["春", "夏", "秋"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "基础款白色T恤", size: "M", imageUrl: "/images/clothes/white-tshirt.jpg" },
      { id: 17, name: "休闲裤", type: "裤装", season: ["春", "秋"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "卡其色休闲裤", size: "32", imageUrl: "/images/clothes/chinos.jpg" }
    ]
  },
  // 搭配方案 10：冬季休闲
  {
    id: 10,
    name: "冬季休闲搭配",
    season: "冬",
    occasionName: "休闲",
    occasion: "休闲",
    image: "/images/clothes/hoodie.jpg",
    clothesNames: "运动卫衣、深蓝色牛仔裤",
    clothes: [
      { id: 9, name: "运动卫衣", type: "上衣", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "连帽卫衣", size: "L", imageUrl: "/images/clothes/hoodie.jpg" },
      { id: 2, name: "深蓝色牛仔裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "修身款牛仔裤", size: "32", imageUrl: "/images/clothes/blue-jeans.png" }
    ]
  },
  // 搭配方案 11：夏季运动
  {
    id: 11,
    name: "夏季运动搭配",
    season: "夏",
    occasionName: "运动",
    occasion: "运动",
    image: "/images/clothes/white-tshirt.jpg",
    clothesNames: "白色棉质T恤、运动裤",
    clothes: [
      { id: 1, name: "白色棉质T恤", type: "上衣", season: ["春", "夏", "秋"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "基础款白色T恤", size: "M", imageUrl: "/images/clothes/white-tshirt.jpg" },
      { id: 13, name: "运动裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "黑色运动裤", size: "L", imageUrl: "/images/clothes/sweatpants.jpg" }
    ]
  },
  // 搭配方案 12：秋季正式
  {
    id: 12,
    name: "秋季正式场合搭配",
    season: "秋",
    occasionName: "正式",
    occasion: "正式",
    image: "/images/clothes/blazer.jpg",
    clothesNames: "休闲西装、西装裤",
    clothes: [
      { id: 8, name: "休闲西装", type: "外套", season: ["春", "秋"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "深蓝色休闲西装", size: "M", imageUrl: "/images/clothes/blazer.jpg" },
      { id: 20, name: "西装裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "黑色西装裤", size: "32", imageUrl: "/images/clothes/suit-pants.jpg" }
    ]
  },
  // 搭配方案 13：春季日常
  {
    id: 13,
    name: "春季日常搭配",
    season: "春",
    occasionName: "日常",
    occasion: "日常",
    image: "/images/clothes/floral-dress.jpg",
    clothesNames: "连衣裙、针织开衫",
    clothes: [
      { id: 7, name: "连衣裙", type: "裙装", season: ["春", "夏"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "碎花连衣裙", size: "S", imageUrl: "/images/clothes/floral-dress.jpg" },
      { id: 12, name: "针织开衫", type: "上衣", season: ["春", "秋"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "蓝色针织开衫", size: "M", imageUrl: "/images/clothes/cardigan.jpg" }
    ]
  },
  // 搭配方案 14：冬季运动
  {
    id: 14,
    name: "冬季运动保暖搭配",
    season: "冬",
    occasionName: "运动",
    occasion: "运动",
    image: "/images/clothes/hoodie.jpg",
    clothesNames: "运动卫衣、运动裤、黑色羽绒服",
    clothes: [
      { id: 9, name: "运动卫衣", type: "上衣", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "连帽卫衣", size: "L", imageUrl: "/images/clothes/hoodie.jpg" },
      { id: 13, name: "运动裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "黑色运动裤", size: "L", imageUrl: "/images/clothes/sweatpants.jpg" },
      { id: 3, name: "黑色羽绒服", type: "外套", season: ["冬"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "长款羽绒服", size: "L", imageUrl: "/images/clothes/black-down-jacket.jpg" }
    ]
  },
  // 搭配方案 15：夏季正式
  {
    id: 15,
    name: "夏季正式场合搭配",
    season: "夏",
    occasionName: "正式",
    occasion: "正式",
    image: "/images/clothes/silk-blouse.jpg",
    clothesNames: "真丝衬衫、半身裙",
    clothes: [
      { id: 10, name: "真丝衬衫", type: "上衣", season: ["春", "夏"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "米色真丝衬衫", size: "S", imageUrl: "/images/clothes/silk-blouse.jpg" },
      { id: 15, name: "半身裙", type: "裙装", season: ["春", "夏", "秋"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "A字型半身裙", size: "S", imageUrl: "/images/clothes/skirt.jpg" }
    ]
  },
  // 搭配方案 16：秋季运动
  {
    id: 16,
    name: "秋季运动搭配",
    season: "秋",
    occasionName: "运动",
    occasion: "运动",
    image: "/images/clothes/hoodie.jpg",
    clothesNames: "运动卫衣、运动裤",
    clothes: [
      { id: 9, name: "运动卫衣", type: "上衣", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "连帽卫衣", size: "L", imageUrl: "/images/clothes/hoodie.jpg" },
      { id: 13, name: "运动裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "黑色运动裤", size: "L", imageUrl: "/images/clothes/sweatpants.jpg" }
    ]
  },
  // 搭配方案 17：春季正式
  {
    id: 17,
    name: "春季正式场合搭配",
    season: "春",
    occasionName: "正式",
    occasion: "正式",
    image: "/images/clothes/blazer.jpg",
    clothesNames: "休闲西装、真丝衬衫、西装裤",
    clothes: [
      { id: 8, name: "休闲西装", type: "外套", season: ["春", "秋"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "深蓝色休闲西装", size: "M", imageUrl: "/images/clothes/blazer.jpg" },
      { id: 10, name: "真丝衬衫", type: "上衣", season: ["春", "夏"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "米色真丝衬衫", size: "S", imageUrl: "/images/clothes/silk-blouse.jpg" },
      { id: 20, name: "西装裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "黑色西装裤", size: "32", imageUrl: "/images/clothes/suit-pants.jpg" }
    ]
  },
  // 搭配方案 18：夏季日常
  {
    id: 18,
    name: "夏季日常搭配",
    season: "夏",
    occasionName: "日常",
    occasion: "日常",
    image: "/images/clothes/white-tshirt.jpg",
    clothesNames: "白色棉质T恤、半身裙",
    clothes: [
      { id: 1, name: "白色棉质T恤", type: "上衣", season: ["春", "夏", "秋"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "基础款白色T恤", size: "M", imageUrl: "/images/clothes/white-tshirt.jpg" },
      { id: 15, name: "半身裙", type: "裙装", season: ["春", "夏", "秋"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "A字型半身裙", size: "S", imageUrl: "/images/clothes/skirt.jpg" }
    ]
  },
  // 搭配方案 19：秋季日常
  {
    id: 19,
    name: "秋季日常搭配",
    season: "秋",
    occasionName: "日常",
    occasion: "日常",
    image: "/images/clothes/plaid-shirt.jpg",
    clothesNames: "格子衬衫、休闲裤",
    clothes: [
      { id: 4, name: "格子衬衫", type: "上衣", season: ["春", "秋"], isDirty: false, isMoldy: true, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "经典红黑格子衬衫", size: "S", imageUrl: "/images/clothes/plaid-shirt.jpg" },
      { id: 17, name: "休闲裤", type: "裤装", season: ["春", "秋"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "卡其色休闲裤", size: "32", imageUrl: "/images/clothes/chinos.jpg" }
    ]
  },
  // 搭配方案 20：冬季正式
  {
    id: 20,
    name: "冬季正式场合搭配",
    season: "冬",
    occasionName: "正式",
    occasion: "正式",
    image: "/images/clothes/wool-coat.jpg",
    clothesNames: "羊毛大衣、高领毛衣",
    clothes: [
      { id: 6, name: "羊毛大衣", type: "外套", season: ["冬"], isDirty: false, isMoldy: false, isDamaged: true, cleaningStatus: "已清洗", maintenanceStatus: "待保养", description: "深灰色羊毛大衣", size: "L", imageUrl: "/images/clothes/wool-coat.jpg" },
      { id: 16, name: "高领毛衣", type: "上衣", season: ["秋", "冬"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "灰色高领毛衣", size: "M", imageUrl: "/images/clothes/turtleneck.jpg" }
    ]
  },
  // 搭配方案 21：春季运动
  {
    id: 21,
    name: "春季运动搭配",
    season: "春",
    occasionName: "运动",
    occasion: "运动",
    image: "/images/clothes/polo-shirt.jpg",
    clothesNames: "POLO衫、运动裤",
    clothes: [
      { id: 19, name: "POLO衫", type: "上衣", season: ["春", "夏", "秋"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "藏青色POLO衫", size: "M", imageUrl: "/images/clothes/polo-shirt.jpg" },
      { id: 13, name: "运动裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: false, isMoldy: false, isDamaged: false, cleaningStatus: "已清洗", maintenanceStatus: "已保养", description: "黑色运动裤", size: "L", imageUrl: "/images/clothes/sweatpants.jpg" }
    ]
  },
  // 搭配方案 22：秋季工作
  {
    id: 22,
    name: "秋季工作搭配",
    season: "秋",
    occasionName: "工作",
    occasion: "工作",
    image: "/images/clothes/trench-coat.jpg",
    clothesNames: "风衣、真丝衬衫、西装裤",
    clothes: [
      { id: 18, name: "风衣", type: "外套", season: ["春", "秋"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "米色风衣", size: "L", imageUrl: "/images/clothes/trench-coat.jpg" },
      { id: 10, name: "真丝衬衫", type: "上衣", season: ["春", "夏"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "米色真丝衬衫", size: "S", imageUrl: "/images/clothes/silk-blouse.jpg" },
      { id: 20, name: "西装裤", type: "裤装", season: ["春", "秋", "冬"], isDirty: true, isMoldy: false, isDamaged: false, cleaningStatus: "待清洗", maintenanceStatus: "待保养", description: "黑色西装裤", size: "32", imageUrl: "/images/clothes/suit-pants.jpg" }
    ]
  }
  // 您可以在这里添加更多固定的搭配方案
];

Page({
  data: {
    // cartGroupData: null, // 注释掉购物车数据字段
    seasons: [
      { label: '全部', value: '' },
      { label: '春季', value: '春' },
      { label: '夏季', value: '夏' },
      { label: '秋季', value: '秋' },
      { label: '冬季', value: '冬' }
    ],
    occasions: [
      { label: '全部', value: '' },
      { label: '日常', value: '日常' },
      { label: '工作', value: '工作' },
      { label: '运动', value: '运动' },
      { label: '正式', value: '正式' }
    ],
    currentSeason: '',
    currentOccasion: '',
    outfitList: [],
    filteredOutfitList: [],
    loading: false,
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    searchValue: '',
    needRefresh: false
  },

  // 调用自定义tabbar的init函数，使页面与tabbar激活状态保持一致
  onShow() {
    console.log('cart page: onShow');
    this.getTabBar().init();
    // 确保每次进入页面都重新加载和过滤搭配列表
    this.loadOutfitList();
  },

  onLoad() {
    console.log('cart page: onLoad');
    // 页面加载时初始化数据
    this.loadOccasions();
    this.loadOutfitList(); // 首次加载列表

    // 在 onLoad 中绑定事件监听器，确保 EventChannel 可用
    if (this.getOpenerEventChannel) {
      const eventChannel = this.getOpenerEventChannel();
      // 确保 EventChannel 对象存在且有 on 方法
      if (eventChannel && typeof eventChannel.on === 'function') {
        eventChannel.on('refreshOutfitList', (data) => {
          console.log('cart page: 收到刷新事件', data);
          if (data && data.updatedOutfit) {
            this.handleOutfitUpdate(data.updatedOutfit, data.isNew);
          } else if (data && data.deletedId) { // 处理删除事件
            this.handleOutfitDelete(data.deletedId);
          } else {
            console.warn('cart page: 刷新事件数据格式不正确', data);
        }
        });
      } else {
        console.warn('cart page: 无法获取 EventChannel 或 EventChannel.on 不可用');
    }
    }
  },

  // 添加处理删除的函数
  handleOutfitDelete(deletedId) {
    console.log('handleOutfitDelete: 开始处理搭配删除', deletedId);
    let outfitList = [...this.data.outfitList];
    const index = outfitList.findIndex(item => item.id === deletedId);
    if (index > -1) {
      outfitList.splice(index, 1);
      console.log('handleOutfitDelete: 从当前列表移除', deletedId);
      this.setData({ 
        outfitList: outfitList 
      }, () => {
        this.filterOutfits(outfitList); // 重新过滤显示
        console.log('handleOutfitDelete: 页面数据已更新', this.data.outfitList);
      });
    } else {
      console.warn('handleOutfitDelete: 未找到需要删除的搭配', deletedId);
    }
  },

  onSeasonChange(e) {
    this.setData({
      currentSeason: e.detail.value,
      // 重置分页和加载状态（尽管静态数据不分页，保持习惯）
      pageNum: 1,
      hasMore: true
    }, () => {
      this.filterOutfits();
    });
  },

  onOccasionSelect(e) {
    const { value } = e.currentTarget.dataset;
    this.setData({ 
      currentOccasion: value,
       // 重置分页和加载状态
      pageNum: 1,
      hasMore: true
    }, () => {
      this.filterOutfits();
    });
  },

  // 按季节和场合过滤搭配列表，并应用搜索
  filterOutfits(list = this.data.outfitList) {
    console.log('filterOutfits: 开始过滤', { currentSeason: this.data.currentSeason, currentOccasion: this.data.currentOccasion, searchValue: this.data.searchValue });
    let filtered = [...list];
    
    // 按季节过滤
    if (this.data.currentSeason) {
      filtered = filtered.filter(item => item.season === this.data.currentSeason);
      console.log('filterOutfits: 按季节过滤后', filtered.length);
    }
    
    // 按场合过滤
    if (this.data.currentOccasion) {
      filtered = filtered.filter(item => item.occasion === this.data.currentOccasion);
      console.log('filterOutfits: 按场合过滤后', filtered.length);
    }

    // 按搜索值过滤
    if (this.data.searchValue) {
      const searchLower = this.data.searchValue.toLowerCase();
      filtered = filtered.filter(item => 
        item.name.toLowerCase().includes(searchLower) ||
        (item.clothesNames && item.clothesNames.toLowerCase().includes(searchLower))
      );
      console.log('filterOutfits: 按搜索值过滤后', filtered.length);
    }

    this.setData({
      filteredOutfitList: filtered
    });
    console.log('filterOutfits: 过滤完成，更新 filteredOutfitList', filtered.length);
  },

  onAddOutfit() {
    wx.navigateTo({
      url: '/pages/outfit/edit/index',
      events: {
        refreshOutfitList: (data) => {
          // 从新建搭配页返回后触发刷新
           console.log('cart page: 收到来自edit页面的refreshOutfitList事件', data);
           if (data && data.updatedOutfit) {
              this.handleOutfitUpdate(data.updatedOutfit, true); // isNew is true
           } else {
              console.warn('cart page: refreshOutfitList事件数据不完整', data);
           }
        }
      }
    });
  },

  onEditOutfit(e) {
    const { id } = e.currentTarget.dataset;
     console.log('cart page: 点击编辑搭配', id);
    wx.navigateTo({
      url: `/pages/outfit/edit/index?id=${id}`,
      events: {
        refreshOutfitList: (data) => {
          // 从编辑搭配页返回后触发刷新
          console.log('cart page: 收到来自edit页面的refreshOutfitList事件', data);
          if (data && data.updatedOutfit) {
             this.handleOutfitUpdate(data.updatedOutfit, false); // isNew is false
          } else {
             console.warn('cart page: refreshOutfitList事件数据不完整', data);
           }
        }
      }
    });
  },

  async onDeleteOutfit(e) {
      const id = e.currentTarget.dataset.id;
    
    try {
      // 等待用户确认删除并获取结果
      const res = await wx.showModal({
        title: '确认删除',
        content: '确定要删除这个搭配吗？',
        confirmText: '删除',
        confirmColor: '#fa4126'
      });
      
      // 检查用户是否点击了确认
      if (res.confirm) {
        console.log('onDeleteOutfit: 用户确认删除', id);

        // 模拟删除成功，实际应用中应调用删除接口
        // await deleteOutfit(id);
  
        // 在静态数据中移除该搭配
        const staticIndex = staticOutfitList.findIndex(item => item.id === id);
        if (staticIndex > -1) {
          staticOutfitList.splice(staticIndex, 1);
          console.log('onDeleteOutfit: 已从静态数据中移除', id);
        } else {
           console.warn('onDeleteOutfit: 未在静态数据中找到需要删除的搭配', id);
        }
  
        // 更新页面列表（即使静态数据中没找到，也尝试从当前页面列表中移除，确保一致性）
        this.handleOutfitDelete(id);

        // 删除成功提示
        Toast({
          context: this,
          selector: '#t-toast',
          message: '删除成功',
          icon: 'success'
        });
      } else if (res.cancel) {
        console.log('onDeleteOutfit: 用户取消删除', id);
        // 用户取消删除，不做任何操作
      }
      
    } catch (error) {
      // 发生其他错误（不是用户取消）
      console.error('onDeleteOutfit: 删除过程中发生错误', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '删除失败', // 可以根据 error 类型显示更具体的错误信息
        icon: 'error'
      });
    }
  },

  previewImage(e) {
    const { src } = e.currentTarget.dataset;
    wx.previewImage({
      current: src,
      urls: [src]
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    console.log('onPullDownRefresh: 下拉刷新');
    // 重置筛选和搜索条件，重新加载列表
    this.setData({
      pageNum: 1,
       hasMore: true,
       searchValue: '',
       currentSeason: '',
       currentOccasion: ''
    }, () => {
      this.loadOutfitList().then(() => {
         wx.stopPullDownRefresh();
       }).catch(() => {
        wx.stopPullDownRefresh();
      });
    });
  },

  // 上拉加载更多 (静态数据不再需要此逻辑)
  onReachBottom() {
    console.log('onReachBottom: 上拉加载 (静态数据无更多)');
    // if (this.data.loading || !this.data.hasMore) return;
    // this.loadMoreOutfits();
  },

  // 加载搭配列表 (现在只加载静态数据)
  loadOutfitList() {
    console.log('loadOutfitList: 开始加载搭配列表 (静态数据)');
    this.setData({ loading: true });
    
    return new Promise((resolve) => {
      setTimeout(() => {
        try {
          // 始终使用最新的静态数据
          const outfits = [...staticOutfitList];
          console.log('loadOutfitList: 从静态数据加载', outfits);
          
          // 处理搭配列表数据，确保季节/场合是字符串
          const processedOutfitList = outfits.map(outfit => {
            // 确保 season, occasion, occasionName 都是字符串
            const season = typeof outfit.season === 'string' ? outfit.season : '';
            const occasion = typeof outfit.occasion === 'string' ? outfit.occasion : '';
            const occasionName = typeof outfit.occasionName === 'string' ? outfit.occasionName : '';

            // 处理衣物列表，确保 clothesNames 存在
             const clothes = outfit.clothes || [];
             const clothesNames = outfit.clothesNames || clothes.map(item => item.name).join('、') || '';

            return {
              ...outfit,
              season,
              occasion,
              occasionName,
              clothes,
              clothesNames
            };
          });

      this.setData({
            outfitList: processedOutfitList,
            filteredOutfitList: processedOutfitList, // 初始显示全部
            loading: false,
            hasMore: false // 由于是静态数据，设置 hasMore 为 false
          });

          console.log('loadOutfitList: 数据加载完成', this.data.outfitList);
          this.filterOutfits(processedOutfitList); // 加载完成后立即应用当前筛选和搜索
          resolve();
    } catch (error) {
          console.error('loadOutfitList: 加载数据时出错', error);
      this.setData({ loading: false });
          resolve();
        }
      }, 0); // 模拟网络延迟
    });
  },

  // 加载更多 (静态数据不再需要)
  // loadMoreOutfits: function() { ... },

  loadOccasions() {
    console.log('loadOccasions: 开始加载场合列表');
    // 模拟异步加载场合数据
    return new Promise((resolve, reject) => {
      setTimeout(() => {
    try {
           // 模拟返回场合列表数据
           const res = { data: [ { label: '日常', value: '日常' }, { label: '工作', value: '工作' }, { label: '运动', value: '运动' }, { label: '正式', value: '正式' } ] };
      // 添加"全部"选项到列表开头
          const occasions = [ { label: '全部', value: '' }, ...(res.data || []) ];
          this.setData({ occasions });
          console.log('loadOccasions: 场合列表加载完成', occasions);
          resolve();
    } catch (error) {
           console.error('loadOccasions: 加载场合列表失败', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '加载场合列表失败',
        icon: 'error'
      });
          reject(error);
    }
      }, 0); // 模拟网络延迟
    });
  },

  // 搜索相关方法
  onSearchInput(e) {
    console.log('onSearchInput: 搜索输入', e.detail.value);
    this.setData({
      searchValue: e.detail.value
    }, () => {
      this.filterOutfits();
    });
  },

  onSearchClear() {
    console.log('onSearchClear: 清除搜索');
    this.setData({
      searchValue: ''
    }, () => {
    this.filterOutfits();
    });
  },

  onSearchSubmit(e) {
    console.log('onSearchSubmit: 提交搜索', e.detail.value);
    this.setData({
      searchValue: e.detail.value
    }, () => {
    this.filterOutfits();
    });
  },

  // 查看搭配详情
  onViewOutfitDetail(e) {
    const { id } = e.currentTarget.dataset;
    console.log('onViewOutfitDetail: 查看搭配详情', id);
    
    // 获取当前搭配数据
    const outfit = this.data.outfitList.find(item => item.id === id);
    if (!outfit) {
      console.warn('onViewOutfitDetail: 未找到搭配数据', id);
      return;
    }

    // 确保衣物数据格式正确
    const processedOutfit = {
      ...outfit,
      clothes: (outfit.clothes || []).map(item => ({
        ...item,
        name: typeof item.name === 'string' ? item.name : (item.name || ''),
        type: typeof item.type === 'string' ? item.type : (item.type || ''),
        season: Array.isArray(item.season) ? item.season.join('、') : (typeof item.season === 'string' ? item.season : ''),
        imageUrl: item.imageUrl || item.image || '/images/default-clothes.png',
        isDirty: !!item.isDirty,
        isMoldy: !!item.isMoldy,
        isDamaged: !!item.isDamaged,
        cleaningStatus: typeof item.cleaningStatus === 'string' ? item.cleaningStatus : '待清洗',
        maintenanceStatus: typeof item.maintenanceStatus === 'string' ? item.maintenanceStatus : '待保养',
        description: typeof item.description === 'string' ? item.description : '',
        size: typeof item.size === 'string' ? item.size : ''
      }))
    };

    // 将搭配数据存储到本地缓存
    wx.setStorageSync('currentOutfitDetail', processedOutfit);

    // 跳转到搭配详情页
    wx.navigateTo({
      url: `/pages/outfit/detail/index?id=${id}`,
      success: () => {
        console.log('onViewOutfitDetail: 跳转成功');
      },
      fail: (error) => {
        console.error('onViewOutfitDetail: 跳转失败', error);
        Toast({
          context: this,
          selector: '#t-toast',
          message: '查看详情失败',
          icon: 'error'
        });
      }
    });
  },

  // 处理搭配更新（新建或编辑返回）
  handleOutfitUpdate(updatedOutfit, isNew) {
    console.log('handleOutfitUpdate: 开始处理搭配更新', { updatedOutfit, isNew });
    console.log('handleOutfitUpdate: 更新前的 staticOutfitList 长度', staticOutfitList.length);
    
    try {
      // 创建 staticOutfitList 的一个可变副本进行操作
      let currentStaticList = [...staticOutfitList];

      // 确保衣物数据格式正确
      const processedClothes = (updatedOutfit.clothes || []).map(item => {
        // 检查 item.name 是否是对象，如果是，提取嵌套的属性
        const actualItem = typeof item.name === 'object' && item.name !== null ? {
          ...item.name,
          // 保留原始 item 中的非对象 name 属性（以防万一）
          ...(typeof item.name !== 'object' ? { name: item.name } : {}),
          // 确保 imageUrl 和 image 存在，优先使用 imageUrl
          imageUrl: item.name.imageUrl || item.name.image || item.imageUrl || item.image || '/images/default-clothes.png'
        } : {
          // 如果 item.name 不是对象，直接使用 item 的属性
          ...item,
           // 确保 imageUrl 和 image 存在，优先使用 imageUrl
          imageUrl: item.imageUrl || item.image || '/images/default-clothes.png'
        };

        return {
          ...actualItem,
          // 确保 name 属性是字符串
          name: typeof actualItem.name === 'string' ? actualItem.name : (actualItem.name || ''),
          // 确保 type 属性是字符串
          type: typeof actualItem.type === 'string' ? actualItem.type : (actualItem.type || ''),
          // 确保 season 属性是数组
          season: Array.isArray(actualItem.season) ? actualItem.season : (typeof actualItem.season === 'string' ? [actualItem.season] : []),
          // 确保其他布尔值属性正确
          isDirty: !!actualItem.isDirty,
          isMoldy: !!actualItem.isMoldy,
          isDamaged: !!actualItem.isDamaged,
           // 确保清洗和保养状态是字符串
          cleaningStatus: typeof actualItem.cleaningStatus === 'string' ? actualItem.cleaningStatus : '待清洗',
          maintenanceStatus: typeof actualItem.maintenanceStatus === 'string' ? actualItem.maintenanceStatus : '待保养',
           // 确保 description 和 size 是字符串
          description: typeof actualItem.description === 'string' ? actualItem.description : '',
          size: typeof actualItem.size === 'string' ? actualItem.size : ''
        };
      });

      console.log('handleOutfitUpdate: 处理后的衣物列表 processedClothes', processedClothes);

      // 确保数据格式正确，与 staticOutfitList 的结构一致
      const formattedOutfit = {
        id: updatedOutfit.id,
        name: updatedOutfit.name,
        description: updatedOutfit.description || '',
        season: Array.isArray(updatedOutfit.seasons) ? updatedOutfit.seasons.join('、') : (updatedOutfit.seasons || ''),
        occasionName: Array.isArray(updatedOutfit.occasions) ? updatedOutfit.occasions.join('、') : (updatedOutfit.occasions || ''),
        occasion: Array.isArray(updatedOutfit.occasions) ? updatedOutfit.occasions.join('、') : (updatedOutfit.occasions || ''),
        image: updatedOutfit.image || (processedClothes[0] && processedClothes[0].imageUrl) || '',
        clothes: processedClothes,
        clothesNames: processedClothes.map(item => item.name.name).join('、'),
        createTime: updatedOutfit.createTime || new Date().toISOString(),
        updateTime: new Date().toISOString()
      };

      console.log('handleOutfitUpdate: 格式化后的搭配数据', formattedOutfit);

      if (isNew) {
        currentStaticList.unshift(formattedOutfit);
      } else {
        const index = currentStaticList.findIndex(item => item.id === updatedOutfit.id);
        if (index !== -1) {
          currentStaticList[index] = formattedOutfit;
        } else {
          currentStaticList.unshift(formattedOutfit);
        }
      }

      // 更新全局的 staticOutfitList
      staticOutfitList.splice(0, staticOutfitList.length, ...currentStaticList);
      console.log('handleOutfitUpdate: 更新后的 staticOutfitList 长度', staticOutfitList.length);

      // 直接更新页面数据，确保立即显示最新列表
      this.setData({
        outfitList: [...staticOutfitList] // 使用更新后的静态列表作为当前列表数据源
      }, () => {
        console.log('handleOutfitUpdate: 页面 outfitList 已更新');
        // 重新过滤显示最新的搭配列表
        this.filterOutfits(this.data.outfitList);
        console.log('handleOutfitUpdate: 页面 filteredOutfitList 已更新');
         // 添加一个小的延迟，有时有助于确保界面渲染
         setTimeout(() => {
            // 可以在这里添加一个 Toast 提示更新成功
             // Toast({ context: this, selector: '#t-toast', message: '搭配列表已更新', icon: 'success' });
         }, 50);
      });

    } catch (error) {
      console.error('handleOutfitUpdate: 处理搭配更新时出错', error);
    }
  },

  onUnload() {
    // 在页面卸载时移除事件监听器
    if (this.getOpenerEventChannel) {
      const eventChannel = this.getOpenerEventChannel();
      if (eventChannel && typeof eventChannel.off === 'function') {
        eventChannel.off('refreshOutfitList');
        console.log('cart page: 移除了 refreshOutfitList 事件监听器');
      }
    }
  },

  async chooseImage() {
    try {
      const res = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed']
      });

      if (res.tempFiles && res.tempFiles.length > 0) {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        
        // 直接更新图片，不进行版本检查
        this.setData({
          'outfitForm.image': tempFilePath
        });
        
        console.log('chooseImage: 图片选择成功', tempFilePath);
      }
    } catch (error) {
      console.error('chooseImage: 选择图片失败', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '选择图片失败',
        icon: 'error'
      });
    }
  },
});

